var express = require('express');
var request = require('request');
const https = require('https');
const url = require('url');
var fs = require('fs');
var app = express();

app.get('/', function (req, res) {
    res.send('hello world');
});
app.get('/scan', function (req, res) {
    res.setHeader("Access-Control-Allow-Origin", "*")
    res.send('hello world');
});

//  这是在测试微信小程序的普通连接二维码的时候，好验证文件Z4NGIAwr2E.txt
app.all('/Z4NGIAwr2E.txt', function (req, res) {
    res.writeHead(200, {
        'Content-Type': 'application/octet-stream',//告诉浏览器这是一个二进制文件
        'Content-Disposition': 'attachment; filename=' + encodeURI("Z4NGIAwr2E.txt"),//告诉浏览器这是一个需要下载的文件
    });//设置响应头
    var readStream = fs.createReadStream("./Z4NGIAwr2E.txt");//得到文件输入流
    // debugger
    readStream.on('data', (chunk) => {
        res.write(chunk, 'binary');//文档内容以二进制的格式写到response的输出流
    });
    readStream.on('end', () => {
        res.end();
    })
});
app.all('/scan/Z4NGIAwr2E.txt', function (req, res) {
    res.writeHead(200, {
        'Content-Type': 'application/octet-stream',//告诉浏览器这是一个二进制文件
        'Content-Disposition': 'attachment; filename=' + encodeURI("Z4NGIAwr2E.txt"),//告诉浏览器这是一个需要下载的文件
    });//设置响应头
    var readStream = fs.createReadStream("./Z4NGIAwr2E.txt");//得到文件输入流
    // debugger
    readStream.on('data', (chunk) => {
        res.write(chunk, 'binary');//文档内容以二进制的格式写到response的输出流
    });
    readStream.on('end', () => {
        res.end();
    })
});
app.all('/Z4NGIAwr2E', function (req, res) {
    res.writeHead(200, {
        'Content-Type': 'application/octet-stream',//告诉浏览器这是一个二进制文件
        'Content-Disposition': 'attachment; filename=' + encodeURI("Z4NGIAwr2E.txt"),//告诉浏览器这是一个需要下载的文件
    });//设置响应头
    var readStream = fs.createReadStream("./Z4NGIAwr2E.txt");//得到文件输入流
    // debugger
    readStream.on('data', (chunk) => {
        res.write(chunk, 'binary');//文档内容以二进制的格式写到response的输出流
    });
    readStream.on('end', () => {
        res.end();
    })
});
app.all('/scan/Z4NGIAwr2E', function (req, res) {
    res.writeHead(200, {
        'Content-Type': 'application/octet-stream',//告诉浏览器这是一个二进制文件
        'Content-Disposition': 'attachment; filename=' + encodeURI("Z4NGIAwr2E.txt"),//告诉浏览器这是一个需要下载的文件
    });//设置响应头
    var readStream = fs.createReadStream("./Z4NGIAwr2E.txt");//得到文件输入流
    // debugger
    readStream.on('data', (chunk) => {
        res.write(chunk, 'binary');//文档内容以二进制的格式写到response的输出流
    });
    readStream.on('end', () => {
        res.end();
    })
});



// --------------- 

// 这是在测试微信获取小程序码的接口B
app.get('/scan2', function (req, res) {

    const post_data = JSON.stringify({
        "path": "pages/TrunkLogin/TrunkLogin",
        "scene":"wwj",
        "width": "430"
    });
    const token = "37_6ZJW1m3SbX6H42UGcFSAi_1U7uPiQFYy4A7GLrt30YtOGtxsCFUkLZKkefY83S2IytWGxqinVCMxapdS-xpg7FntjXA_PjVotWYgQ51haOM8JTZIk1D6Nrqop1wJgmQRumCHPYIDhyUNEeD7QDShAAABOD"
    
    let options = url.parse("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token);
    options = Object.assign(options, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': post_data.length
        }
    });
    fun()
    async function fun() {

        // 获取图片二进制流
        const { imgBuffer, contentType } = await new Promise((resolve, reject) => {
            let req = https.request(options, (res) => {
                let resData = '';
                res.setEncoding("binary");
                res.on('data', data => {
                    resData += data;
                });
                res.on('end', () => {
                    // 微信api可能返回json，也可能返回图片二进制流。这里要做个判断。
                    const contentType = res.headers['content-type'];
                    if (!contentType.includes('image')) {
                        console.log('获取小程序码图片失败，微信api返回的json为：')
                        console.log(JSON.parse(resData))
                        return resolve(null);
                    }
                    const imgBuffer = Buffer.from(resData, 'binary');   
                    resolve({ imgBuffer, contentType });
                });
            });
            req.on('error', (e) => {
                console.log('获取微信小程序图片失败')
                console.error(e);
            });
            req.write(post_data);   // 写入 post 请求的请求主体。
            req.end();
        }).catch(() => {
            return null;
        });

        if (imgBuffer == null) {
            res.send('hello world2111');
            return;
        } else {
            res.send(imgBuffer);
        }
    }

});

app.listen(8080, function () {
    console.log('访问```：127.0.0.1:8080');
});